package com.hengpeng.itfints.service.account.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.itfinbase.en.TransType;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.AccountLog;
import com.hengpeng.itfints.service.ServiceFactory;
import com.hengpeng.itfints.service.account.AccountService;

@Lazy
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private ServiceFactory serviceFactory;

    @Override
    public Account getAccount(Long userId) {
        DynamicQuery query = new DynamicQuery(Account.class);
        query.eq("userId", userId);
        return serviceFactory.getPersistService().getEntity(query, Account.class);
    }

    @Override
    public ServiceResult<List<AccountLog>> queryAccountLogList(Long userId, TransType transType, String queryTime,
            Integer curPage, Integer pageSize) {
        DynamicQuery query = new DynamicQuery(AccountLog.class);
        if (userId != null) {
            query.eq("userId", userId);
        }
        if (transType != null) {
            query.eq("transType", transType);
        }
        if ("three_day".equals(queryTime)) {// 查询三天以内的记录
            query.ge("createTime", DateTimeUtil.addDate(new Date(), -3));
        } else if ("one_week".equals(queryTime)) {// 查询一周以内的记录
            query.ge("createTime", DateTimeUtil.addDate(new Date(), -7));
        } else if ("one_month".equals(queryTime)) {// 查询一个月之内的记录
            query.ge("createTime", DateTimeUtil.addDate(new Date(), -30));
        } else if ("three_month".equals(queryTime)) {// 查询三个月之内的记录
            query.ge("createTime", DateTimeUtil.addDate(new Date(), -90));
        } else {// 默认显示一周的记录
            query.ge("createTime", DateTimeUtil.addDate(new Date(), -7));
        }
        query.desc("createTime");

        query.setPageIndex(curPage);
        query.setPageSize(pageSize);
        query.setIsSearchTotalCount(true);
        query.setQueryType(QueryType.JDBC);
        QueryResult<AccountLog> result = serviceFactory.getPersistService().findWithPage(AccountLog.class, query);

        Long count = result.getTotalCount();
        ServiceResult<List<AccountLog>> serviceResult = new ServiceResult<List<AccountLog>>();// 设置返回值
        serviceResult.setReturnValue(result.getResults());
        serviceResult.setReturnListSize(count.intValue());
        return serviceResult;
    }

}
